<template>
  <a-dropdown :arrow="true" placement="bottom" trigger="click">
    <span style="color: rgba(0, 0, 0, 0.88); cursor: pointer; font-size: 16px">
      <MoreOutlined></MoreOutlined>
    </span>
    <template #overlay>
      <a-menu
        v-model:selectedKeys="current"
        :items="menuItems"
        @click="click"
      />
    </template>
  </a-dropdown>
</template>
<script setup>
import { MoreOutlined } from '@ant-design/icons-vue'
import { ref, watch } from 'vue'
import { useDataSource } from './provide-context.js'
let dataSource = useDataSource()
// 外部参数
let props = defineProps({
  data: { type: Object, default: () => {} },
})

let current = ref([])
// 层级沿用可选项目
let allPrjNames = ref([])
dataSource.value.forEach(item => {
  if (item.id !== props.data.id) {
    let newItem = { key: item.id, label: item.title, title: item.title }
    allPrjNames.value.push(newItem)
  }
})

// 菜单禁用
let disabledPublish = ref(false)
let disabledUsePrj = ref(false)

let menuItems = ref([])

watch(
  () => props.data,
  newValue => {
    disabledPublish.value = newValue.publishedStatus === 1 ? true : false
    disabledUsePrj.value =
      newValue.publishedStatus === 1 // 项目已发布禁用
        ? true
        : allPrjNames.value.length > 0 // 不存在可沿用的项目禁用
          ? false
          : true
    menuItems.value = [
      {
        key: 'renamePrj',
        label: '修改项目名称',
        title: '修改项目名称',
        disabled: disabledPublish.value,
      },
      {
        key: 'usePrj',
        label: '层级结构沿用',
        title: '层级结构沿用',
        disabled: disabledUsePrj.value,
        children: allPrjNames,
        popupOffset: [0, 0], // 子菜单偏移量
      },
      {
        key: 'addSub',
        label: '添加子集',
        title: '添加子集',
      },
      {
        key: 'deletePrj',
        label: '删除项目',
        title: '删除项目',
      },
      {
        key: 'publishPrj',
        label: '发布',
        title: '发布',
        disabled: disabledPublish.value,
      },
    ]
  },
  { deep: true, immediate: true },
)

let emit = defineEmits(['menuClick'])
let click = ({ item, key, keyPath }) => {
  emit('menuClick', {
    key: keyPath[0],
    usePrjId: keyPath.length > 1 && keyPath[0] == 'usePrj' ? keyPath[1] : null,
    usePrjName:
      keyPath.length > 1 && keyPath[0] == 'usePrj' ? item.title : null,
  })
}
</script>

<style lang="less" scoped>
/* 移除子菜单项上的箭头 */
:deep(.ant-dropdown-menu-submenu-arrow) {
  display: none !important;
}
:deep(.dropdown-menu-submenu .submenu) {
  margin-left: 50px; /* 调整这个值来增加或减少左侧间距 */
}
</style>
